package com.itheima.day13.thread.test10;

public class MyRubbable implements Runnable {
    private int tickets = 100;

    @Override
    public void run() {
        while (true) {
            if ("窗口一".equals(Thread.currentThread().getName())) {
                // 同步方法
                boolean boo = synchronizedMethod();
                if (boo)
                    break;
            }
            if ("窗口二".equals(Thread.currentThread().getName())) {
                // 同步代码块
                synchronized(this) {
                    if (tickets == 0) {
                        break;
                    }
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    tickets--;
                    System.out.println(Thread.currentThread().getName() + " 正在买票，还剩 " + tickets + " 张票。");
                }
            }
        }
    }

    private synchronized boolean synchronizedMethod() {
        if (tickets == 0) {
            return true;
        } else {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tickets--;
            System.out.println(Thread.currentThread().getName() + " 正在买票，还剩 " + tickets + " 张票。");
            return false;
        }
    }
}
